package org.fxd.zweixin.busi_wx;

import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.tmsps.ne4spring.utils.WebUtil;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.HashKit;
import com.jfinal.kit.StrKit;
import com.jfinal.weixin.sdk.api.ApiConfig;
import com.jfinal.weixin.sdk.api.ApiConfigKit;
import com.jfinal.weixin.sdk.api.JsTicket;
import com.jfinal.weixin.sdk.api.JsTicketApi;
import com.jfinal.weixin.sdk.api.JsTicketApi.JsApiType;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.dreamlu.weixin.annotation.WxApi;

@Api(description = "微信JSAPI")
@WxApi("/weixin/api/js")
public class WeixinJsApiController {

	private Logger logger = LoggerFactory.getLogger(this.getClass());

	@ApiOperation(value = "获取js的配置文件")
	@GetMapping("/getConfig")
	@ResponseBody
	public String getConfig() {
		HttpServletRequest request = WebUtil.getRequest();
		// 1.拼接url（当前网页的URL，不包含#及其后面部分）
		String _wxShareUrl = request.getHeader("Referer");
		if (StrKit.notBlank(_wxShareUrl)) {
			_wxShareUrl = _wxShareUrl.split("#")[0];
		} else {
//		    return;
		}
		// 先从参数中获取，获取不到时从配置文件中找
		String appId = request.getParameter("appId");
		if (StrKit.isBlank(appId)) {
//			appId = PropKit.get("appId");
			ApiConfig ac = ApiConfigKit.getApiConfig();
			appId = ac.getAppId();
		}
		logger.info("appid={}", appId);
		// 方便测试 1.9添加参数&test=true
		String isTest = request.getParameter("test");
		if (null == isTest || !isTest.equalsIgnoreCase("true")) {
			isTest = "false";
		}

		ApiConfigKit.setThreadLocalAppId(appId);
		String _wxJsApiTicket = "";
		try {
			JsTicket jsTicket = JsTicketApi.getTicket(JsApiType.jsapi);
			_wxJsApiTicket = jsTicket.getTicket();
		} finally {
			ApiConfigKit.removeThreadLocalAppId();
		}

		Map<String, String> _wxMap = new TreeMap<String, String>();
		// noncestr
		String _wxNoncestr = StrKit.getRandomUUID();
		// timestamp
		String _wxTimestamp = (System.currentTimeMillis() / 1000) + "";

		// 参数封装
		_wxMap.put("noncestr", _wxNoncestr);
		_wxMap.put("timestamp", _wxTimestamp);
		_wxMap.put("jsapi_ticket", _wxJsApiTicket);
		_wxMap.put("url", _wxShareUrl);

		// 加密获取signature
		StringBuilder _wxBaseString = new StringBuilder();
		for (Entry<String, String> param : _wxMap.entrySet()) {
			_wxBaseString.append(param.getKey()).append("=").append(param.getValue()).append("&");
		}
		String _wxSignString = _wxBaseString.substring(0, _wxBaseString.length() - 1);
		// signature
		String _wxSignature = HashKit.sha1(_wxSignString);

		// https://gitee.com/jfinal/jfinal-weixin/blob/master/src/main/webapp/jsp/js_sdk.jsp
		// ==========================以上为 jfinal weixin 源文件==================================
		JSONObject result = new JSONObject();
		result.put("isTest", isTest);
		result.put("appId", appId);
		result.put("_wxTimestamp", _wxTimestamp);
		result.put("_wxNoncestr", _wxNoncestr);
		result.put("_wxSignature", _wxSignature);
		logger.info(result.toJSONString());
		return result.toJSONString();
	}

}
